import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'umi';
import useResizeObserver from '@react-hook/resize-observer';
import { kLineIcon } from '@/assets';
import { getCssVariableValue } from '@/utils/utils';
import { useThemeChange } from '@/hooks';

import styles from './index.less';

export const RollingEcharts = (props) => {
  const target = React.useRef(null);
  const [chartIns, setChartIns] = useState();
  const [size, setSize] = useState({});
  const { theme } = useThemeChange();

  // 监听容器尺寸变化
  useResizeObserver(target, (entry) => setSize(entry.contentRect));

  // 当容器尺寸发生改变时，重新渲染echarts图
  useEffect(() => {
    if (chartIns && size.width) {
      chartIns.resize();
    }
  }, [size.width]);

  // 当echart图数据发生变化时，重新初始化echarts图
  useEffect(() => {
    if (!props.rollingChartData) return;
    setTimeout(() => {
      initEcharts();
    }, 2);
  }, [props.rollingChartData, theme]);

  const initEcharts = () => {
    let {
      xData,
      floorPrices,
      ceilingPrices,
      proposedPrices,
      weightedAveragePrices,
      medianPrices,
      lowestPrices,
      highestPrices,
      totalVolumes,
    } = props.rollingChartData;

    var chartDom = document.getElementById('echarts');
    var myChart = echarts.init(chartDom);
    setChartIns(myChart);
    myChart.setOption(
      {
        animation: false,
        color: ['#F4903D', '#F9DABC', '#C1D1FA', '#F5BE15'],
        legend: {
          bottom: 0,
          textStyle: {
            color: '#A7A8A9',
          },
          left: 'center',
          itemGap: 13,
          itemWidth: 16,
          itemHeight: 8,
          data: [
            {
              name: '日滚电价',
              icon: 'image://' + kLineIcon + '',
            },
            '上限价格',
            '下限价格',
            '日前电价',
            '成交电量(日均)',
          ],
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#161A1D',
          borderColor: 'transparent',
          textStyle: {
            color: '#d3d4d4',
          },

          formatter: (params) => {
            let kLinePart = [
              {
                name: '算数平均价',
                index: 2,
              },
              {
                name: '中位数价格',
                index: 1,
              },
              {
                name: '最低价格',
                index: 3,
              },
              {
                name: '最高价格',
                index: 4,
              },
            ];
            let kLinePartString = [];
            let upPart = ['上限价格', '下限价格', '日前电价'];
            let upPartString = [];
            let downPart = ['成交电量(日均)'];
            let downPartString = [];

            params.forEach((paramsItem) => {
              if ('日滚电价' === paramsItem.seriesName) {
                kLinePart.forEach((kLineItem) => {
                  kLinePartString.push(`
                    <div style="width: 200px; height:24px; line-height: 24px; display:flex; justify-content:space-between;">
                      <span>${paramsItem.marker} ${kLineItem.name}</span>
                      <span>${paramsItem.data[kLineItem.index].toFixed(2)}</span>
                    </div>
                  `);
                });
              }
            });
            upPart.forEach((upItem) => {
              params.forEach((paramsItem) => {
                if (upItem === paramsItem.seriesName) {
                  upPartString.push(`
                    <div style="width: 200px; height:24px; line-height: 24px; display:flex; justify-content:space-between;">
                      <span>${paramsItem.marker} ${paramsItem.seriesName}</span>
                      <span>${paramsItem.data.toFixed(2)}</span>
                    </div>
                  `);
                }
              });
            });
            downPart.forEach((downItem) => {
              params.forEach((paramsItem) => {
                if (downItem === paramsItem.seriesName) {
                  downPartString.push(`
                    <div style="width: 200px; height:24px; line-height: 24px; display:flex; justify-content:space-between;">
                      <span>${paramsItem.marker} ${paramsItem.seriesName}</span>
                      <span>${paramsItem.data.toFixed(3)}</span>
                    </div>
                  `);
                }
              });
            });
            let str = `
              <div style="color: #7A7D7F;">${params[0].name}</div>
                <div style="color: #A7A8A9;">
            `;
            str += kLinePartString.join('');
            str += upPartString.join('');
            if (kLinePartString.length + upPartString.length && downPartString.length) {
              str += `
                <div style="width: 200px; height:0; border-top:1px solid #4E5154; margin: 6px 0;"></div>
              `;
            }
            str += downPartString.join('');
            str += `</div>`;
            return str;
          },
        },
        axisPointer: {
          link: [
            {
              xAxisIndex: 'all',
            },
          ],
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
            type: 'solid',
          },
        },
        toolbox: {
          show: false,
        },
        grid: [
          {
            top: '28',
            left: '52',
            right: '0',
            height: '365',
          },
          {
            left: '52',
            right: '0',
            top: '440',
            height: '150',
          },
        ],
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
            axisTick: {
              alignWithLabel: true,
            },
            axisPointer: {
              type: 'line',
              lineStyle: {
                type: 'solid',
                color: getCssVariableValue('--chart-x-line'),
              },
            },
          },
          {
            type: 'category',
            gridIndex: 1,
            data: xData,
            axisLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisLabel: {
              show: false,
            },
            axisTick: {
              show: false,
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            nameTextStyle: {
              color: getCssVariableValue('--chart-font-color'),
            },
            // scale: true,
            axisLine: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
          },
          {
            gridIndex: 1,
            type: 'value',
            nameTextStyle: {
              color: getCssVariableValue('--chart-font-color'),
            },
            // scale: true,
            axisLine: {
              show: false,
            },
            splitLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
          },
        ],
        series: [
          {
            name: '日滚电价',
            type: 'candlestick',
            barWidth: '50%',
            lineStyle: {
              width: 1,
            },
            itemStyle: {
              color: '#E86452',
              color0: '#67DCAB',
            },
            data: (() => {
              let arr = [];
              for (let i = 0; i < 24; i++) {
                arr.push([
                  medianPrices[i],
                  weightedAveragePrices[i],
                  lowestPrices[i],
                  highestPrices[i],
                ]);
              }
              return arr;
            })(),
          },
          {
            name: '上限价格',
            type: 'line',
            data: floorPrices,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 1,
              type: 'dashed',
              opacity: 0.5,
            },
            emphasis: {
              scale: false,
              lineStyle: {
                width: 1,
              },
            },
            itemStyle: {
              opacity: 0,
            },
          },
          {
            name: '下限价格',
            type: 'line',
            data: ceilingPrices,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 1,
              type: 'dashed',
              opacity: 0.5,
            },
            emphasis: {
              scale: false,
              lineStyle: {
                width: 1,
              },
            },
            itemStyle: {
              opacity: 0,
            },
          },
          {
            name: '日前电价',
            type: 'line',
            data: proposedPrices,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              width: 1,
              type: 'dashed',
              opacity: 0.5,
            },
            emphasis: {
              scale: false,
              lineStyle: {
                width: 1,
              },
            },
            itemStyle: {
              opacity: 0,
            },
          },
          {
            name: '成交电量(日均)',
            type: 'bar',
            barWidth: '50%',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: totalVolumes,
          },
        ],
      },
      true,
    );
  };

  return (
    <div ref={target} id="echarts" className={styles.RollingEcharts}>
      {''}
    </div>
  );
};

const mapStateToProps = ({ mediumAndLongTermMarket }) => ({
  rollingChartData: mediumAndLongTermMarket.rollingChartData,
});

const mapDispatchToProps = {};

export default connect(mapStateToProps, mapDispatchToProps)(RollingEcharts);
